<?php

namespace App\Models;

use App\Traits\HasDateTimeFormatter;
use App\Traits\Ownable;
use Illuminate\Database\Eloquent\Casts\Attribute;

use Illuminate\Database\Eloquent\Model;

class UserMoneyWithdraw extends Model
{
    const SUCCESS = 1; // 提现成功
    const PROCESSING = 0; // 提现中
    const FAIL = -1; // 提现失败

    use HasDateTimeFormatter, Ownable;

    protected $table = 'users_money_withdraw';

    protected $casts = [
        'user_id' => 'integer',
        'status' => 'integer',
        'price' => 'float',
    ];

    protected $appends = ['status_name'];

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function user()
    {
        return $this->belongsTo(User::class, 'user_id');
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function org() {
        return $this->hasOne(Org::class, 'org_code', 'org_code');
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function orgRoot() {
        return $this->hasOne(Org::class, 'org_code', 'org_root');
    }

    /**
     */
    protected function statusName(): Attribute
    {
        return Attribute::make(
            get: function ($value, $attributes) {
                $def = [
                    self::SUCCESS => '提现成功',
                    self::PROCESSING => '提现中',
                    self::FAIL => '提现失败'
                ];

                return $def[$attributes['status']] ?? '';
            },
        );
    }

    /**
     * 获取提现中的金额
     */
    static function lockedMoney($uid)
    {
        return self::where('user_id', $uid)
            ->where('status', UserMoneyWithdraw::PROCESSING)->sum('money');
    }
}
